package com.sy.module_clockin

import android.view.View
import androidx.lifecycle.ViewModelProvider
import com.alibaba.android.arouter.facade.annotation.Route
import com.blankj.utilcode.util.LogUtils
import com.fenghuajueli.libbasecoreui.dialog.CommonTipsDialog
import com.fenghuajueli.libbasecoreui.utils.MmkvUtils
import com.fenghuajueli.libbasecoreui.viewmodel.BaseViewModelFragment2
import com.fenghuajueli.module_route.ClockInModuleRoute
import com.haibin.calendarview.Calendar
import com.haibin.calendarview.CalendarView
import com.sy.module_clockin.annotation.ClockInType
import com.sy.module_clockin.databinding.ModuleClockinFragmentRecordBinding
import com.sy.module_clockin.databinding.ModuleClockinItemRecordBinding
import com.sy.module_clockin.db.dbsheet.ClockInData
import com.sy.module_clockin.entity.ContinuesDay
import com.sy.module_clockin.model.ClockInModel
import com.sy.module_clockin.recycler.*
import com.sy.module_clockin.utils.TimeUtils
import java.text.SimpleDateFormat
import java.util.*


@Route(path = ClockInModuleRoute.CLOCKIN_RECORD_PAGE)
class ClockinRecordFragment : BaseViewModelFragment2<ClockInModel, ModuleClockinFragmentRecordBinding>() {
    private val TAG = "ClockinRecordFragment"

    private lateinit var adapter: ViewBindAdapter<ClockInData, ModuleClockinItemRecordBinding>
    private val format by lazy { SimpleDateFormat("HH:mm", Locale.getDefault()) }

    override fun createViewModel(): ClockInModel {
        return ViewModelProvider(this, defaultViewModelProviderFactory).get(ClockInModel::class.java)
    }

    override fun createViewBinding(): ModuleClockinFragmentRecordBinding {
        return ModuleClockinFragmentRecordBinding.inflate(layoutInflater, null, false)
    }

    override fun initView(containerView: View?) {
        binding.btnBack.setOnFastClickListener { requireActivity().finish() }

        binding.calendarView.setOnMonthChangeListener { year, month ->
            updataCalendarBar(month, year)
        }

        binding.calendarView.setOnCalendarSelectListener(object : CalendarView.OnCalendarSelectListener {
            override fun onCalendarOutOfRange(calendar: Calendar?) = Unit
            override fun onCalendarSelect(calendar: Calendar?, isClick: Boolean) {
                calendar?.apply {
                    LogUtils.d("onCalendarSelect --> ${calendar.year}年${calendar.month}月${calendar.day}日")
                    val (monthStart, monthEnd) = TimeUtils.getMonthStartEnd(year, month - 1, day)
                    model.getClockInByTimeRange(requireContext(), monthStart, monthEnd).observe(this@ClockinRecordFragment, {
                        initClockIns(it)
                    })
                }
            }
        })

        adapter = binding.rclMonthWeekData.bindAdapter<ClockInData, ModuleClockinItemRecordBinding> {
            onBindView { itemViewHolder, itemData, position ->

                itemViewHolder.tvDesc.text = itemData.clockInDescription
                val instance = java.util.Calendar.getInstance()
                instance.timeInMillis = itemData.recordTime

                itemViewHolder.tvTime.text = format.format(instance.time)

                when (itemData.clockInType) {
                    ClockInType.CLOCKIN_TYPE_GET_UP_EARLY -> {
                        itemViewHolder.clContainer.setBackgroundResource(R.mipmap.module_clockin_cumulative_bg_01)
                    }

                    ClockInType.CLOCKIN_TYPE_MOVEMENT -> {
                        itemViewHolder.clContainer.setBackgroundResource(R.mipmap.module_clockin_cumulative_bg_02)
                    }

                    ClockInType.CLOCKIN_TYPE_DRINK_WATER -> {
                        itemViewHolder.clContainer.setBackgroundResource(R.mipmap.module_clockin_cumulative_bg_03)
                    }

                    ClockInType.CLOCKIN_TYPE_READING -> {
                        itemViewHolder.clContainer.setBackgroundResource(R.mipmap.module_clockin_cumulative_bg_04)
                    }
                }

                itemViewHolder.btnDelete.setOnFastClickListener {
                    CommonTipsDialog(requireContext(), "是否删除").apply {
                        setConfirmListener {
                            model.deleteClockInData(requireContext(), itemData)
                            adapter.dataList.removeAt(position)
                            adapter.notifyDataSetChanged()
                        }
                        show()
                    }
                }
            }
        }


        updataCalendarBar(binding.calendarView.curMonth, binding.calendarView.curYear)

        binding.tvYear.setOnFastClickListener {
            binding.calendarView.scrollToCurrent()
        }

        binding.tvPreMonth.setOnFastClickListener {
            binding.calendarView.scrollToPre()
        }

        binding.tvNextMonth.setOnFastClickListener {
            binding.calendarView.scrollToNext()
        }


        val (monthStart, monthEnd) = TimeUtils.getMonthStartEnd(binding.calendarView.curYear, binding.calendarView.curMonth - 1, binding.calendarView.curDay)
        model.getClockInByTimeRange(requireContext(), monthStart, monthEnd).observe(this@ClockinRecordFragment, {
            initClockIns(it)
        })

        model.schemeDateLiveData.observe(this, {
            binding.calendarView.setSchemeDate(it)
        })


        model.getClockInCount(requireContext()).observe(this, {
            val continuesDay = MmkvUtils.get("Continuous", ContinuesDay::class.java)
            binding.tvAccumulate.text = "${continuesDay?.accumulateNum ?: 0}"
            binding.tvContinuous.text = "${continuesDay?.continuesNum ?: 0}"
        })


    }

    private fun initClockIns(list: List<ClockInData>) {
        if (list.isNullOrEmpty()) {
            binding.groupEmpty.show()
            binding.rclMonthWeekData.hide()
        } else {
            val select = binding.calendarView.selectedCalendar
            val (dayStart, dayEnd) = TimeUtils.getDayStartEnd(select.year, select.month-1, select.day)
            adapter.dataList.clear()
            adapter.dataList.addAll(list.filter { it.recordTime in dayStart..dayEnd })
            adapter.notifyDataSetChanged()
            binding.groupEmpty.hide()
            binding.rclMonthWeekData.show()
            model.initSchemeDate(list,binding.calendarView)
        }
    }


    private fun updataCalendarBar(month: Int, year: Int) {
        binding.tvYear.text = "${resources.getStringArray(R.array.module_clockin_lunar_first_of_month)[month - 1]} ${year}"
    }

    override fun initData() {

    }

}


